package com.kzy.demoadmin.web.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kzy.demoadmin.web.entity.BookType;
import com.kzy.demoadmin.web.entity.BookTypeQuery;
import com.kzy.demoadmin.web.exception.BizException;
import com.kzy.demoadmin.web.mapper.BookTypeMapper;
import com.kzy.demoadmin.web.service.BookTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 图书分类服务实现类
 */
@Service
public class BookTypeServiceImpl implements BookTypeService {

    @Autowired
    private BookTypeMapper bookTypeMapper;

    @Override
    public int addBookType(BookType bookType) {
        // 校验分类名称不为空
        if (bookType.getName() == null || bookType.getName().trim().isEmpty()) {
            throw new BizException("分类名称不能为空");
        }
        return bookTypeMapper.insert(bookType);
    }

    @Override
    public int deleteBookTypeById(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("ID不能为空");
        }
        // 先查询是否存在
        BookType bookType = bookTypeMapper.selectById(id);
        if (bookType == null) {
            throw new BizException("该分类不存在");
        }
        return bookTypeMapper.deleteById(id);
    }

    @Override
    public int updateBookType(BookType bookType) {
        if (bookType.getId() == null) {
            throw new BizException("ID不能为空");
        }
        // 校验分类是否存在
        BookType existType = bookTypeMapper.selectById(bookType.getId());
        if (existType == null) {
            throw new BizException("该分类不存在");
        }
        // 校验名称不为空
        if (bookType.getName() == null || bookType.getName().trim().isEmpty()) {
            throw new BizException("分类名称不能为空");
        }
        return bookTypeMapper.update(bookType);
    }

    @Override
    public BookType getBookTypeById(Integer id) {
        if (id == null) {
            throw new BizException("ID不能为空");
        }
        return bookTypeMapper.selectById(id);
    }

    @Override
    public PageInfo<BookType> getAllBookTypes(BookTypeQuery query) {
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<BookType> list = bookTypeMapper.selectAll(query);
        return new PageInfo<>(list);
    }

    @Override
    public List<BookType> getAll() {
        return bookTypeMapper.selectAll(null);
    }
}